<?php
/* +----------------------------------------------------------------------
// | 	xaoam.com
// |	author:am
// |	gitee:https://gitee.com/xaoam/amAdmin
// |	email:hi@xaoam.com
// |	
// +----------------------------------------------------------------------*/
namespace app\admin\controller;
use think\Controller;
use think\Db;
use Casbin;

class Auth extends Base {

    public function initialize(){
        parent::initialize();
		$this->reJson= ['code'=>0,'msg'=>'操作失败','data'=>''];
    }
	public function lists($id){
		$res = Db::name('rule')->where('id',$id)->select();
		return $res;
	}
	public function edit(){
		if(request()->isPost()){
			$d = request()->param();
			$res = null;
			$res = 	Casbin::DeletePermissionsForUser($d['id']); /*先删除*/
			if($d['admin'] == 0){
				return json(['code'=>0,'msg'=>'普通用户,无法增加任何权限哦!']);
			}
			if(isset($d['id']) && isset($d['ids'])){
					$lists = Db::name('node')->where('id','in',$d['ids'])
											->select();
					foreach($lists as $key=>$row){
						$str = $row['module_name'] . '/' . $row['control_name'] . '/' . $row['action_name'];
						$res = Casbin::addPermissionForUser($d['id'], $str); /*增加*/
						$res = $this->addBasicRule($d['id']);/*是管理员基本权限*/
					}
			}elseif(isset($d['id'])){
				/*权限为空时,管理员基本权限*/
				$res = $this->addBasicRule($d['id']);
			}
			if($res){
				$this->reJson['code'] = 200;
				$this->reJson['msg']= '操作成功!';
			}
		}else{
			$d = request()->param();
			if(isset($d['id']) && isset($d['user'])){
				if($d['id'] == 1){
					$this->reJson['msg']= '默认管理员权限无需编辑!';
				}else{
				 $res = Db::name('user')->where(['id'=>$d['id'],'username'=>$d['user']])->find();
					$this->assign('user',$res);
					$this->assign('checked',$this->getAuthChecked($d['id']));
					return $this->fetch();	
				}
			
			}
		}
		return json($this->reJson);
	}
	protected function getAuthChecked($id){
		$node_arr = [];
		$node = [];
		$checked ='[]';
		$lists =  Casbin::GetFilteredNamedPolicy('p',0,$id);
				if(!empty($lists)){
					foreach(array_column($lists, 1) as $key=>$row){
						$node_arr[$key] = explode("/",$row);
						$node[$key]['m'] = $node_arr[$key][0];
						$node[$key]['c'] = $node_arr[$key][1];
						$node[$key]['a'] = $node_arr[$key][2];
					foreach($node as $key=>$row){
						$resNode[$key] = Db::name('node')->where([['module_name','=',$node[$key]['m']],['control_name','=',$node[$key]['c']],['action_name','=',$node[$key]['a']]])->value('id');
					}
				$checked= json_encode($resNode);
					}
				}
		return $checked;
	}
}
